﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using XChip_Common;
using XChipTool.Enties;
using System.Configuration;
using BinAnalysisHelp;

namespace XChipTool
{
    public partial class XChip_Lite_Ynr : DevExpress.XtraEditors.XtraUserControl
    {
  
        public SerialPort sPortTemp { get; set; }
        public parameter_exportManager Pe_dal { get; private set; }

        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        List<string> listfiltration = new List<string> { "slope_i", "scale_ynr", "scale_enh", "scale_cnr_i" };
        private addressregisterManager aBll;
        private List<addressregister> XChipYnr;
        private List<addressregister> XChipCnr;
        private List<addressregister> XChipDnr;
        private string ColorOrGray = "Color";
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        public XChip_Lite_Ynr()
        {
            InitializeComponent();
        }
        public XChip_Lite_Ynr(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipYnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "YNR" ));
            XChipCnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "CNR"));
            XChipDnr = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "DNR" || c.Classify == "Common"));
            InitializeComponent();
        }
        private void XChip_Reg_Ynr_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {
                for (int i = 0; i < XChipYnr.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipYnr[i].NameType);

                    var col = this.Controls.Find(type, true);


                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";
                            if (!string.IsNullOrEmpty(XChipYnr[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipYnr[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipYnr[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipYnr[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipYnr[i].Bits, XChipYnr[i].Bit_Wide, XChipYnr.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
                }

                for (int i = 0; i < XChipCnr.Count; i++)
                {

                    var type = AppHelper.NameTypeToString(XChipCnr[i].NameType);
                    //加上单选框的_en
                    if (XChipCnr[i].ControlType == "1")
                    {
                        type = XChipCnr[i].NameType;
                    }
                    var col = this.Controls.Find(type, true);


                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";
                            if (!string.IsNullOrEmpty(XChipCnr[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipCnr[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipCnr[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipCnr[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipCnr[i].Bits, XChipCnr[i].Bit_Wide, XChipCnr.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
                }
            });
            });
        }
        private long GetYNRRegister(string nameType)
        {
            
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipYnr.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private void SetYNRRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (IsUsbOpen)
            {
               

                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                if (isRead) return;
                
                if (null != BinHelp.lspList)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }
            }
            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
        }


      

       

        private void scale_ynr_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
           
            if (XChipYnr.Exists(c => c.NameType.ToLower() == $"scale_ynr_man_en".ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == $"scale_ynr_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_ynr_man_en.Checked);
                SetYNRRegister(model, Val);
            }
            EnShowHide();
        }

        private void scale_enh_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            
            if (XChipYnr.Exists(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_enh_man_en.Checked);
                SetYNRRegister(model, Val);
            }
            EnShowHide();
        }
        private void scale_ynr0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            
            if (XChipYnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYNRRegister(model, Val);
            }

        }

        private void scale_ynr0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_ynr0_KeyDown(sender, keyEnter);
        }

        private void scale_enh0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
             
            if (XChipYnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYNRRegister(model, Val);
            }
            if (XChipYnr.Exists(c => c.NameType.ToLower() == (txtEdit.Name + "firmware_" + "Gray").ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == (txtEdit.Name + "firmware_" + "Gray").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYNRRegister(model, Val);
            }
            if (XChipYnr.Exists(c => c.NameType.ToLower() == (txtEdit.Name + "firmware_" + "Color").ToLower()))
            {
                var model = XChipYnr.Find(c => c.NameType.ToLower() == (txtEdit.Name + "firmware_" + "Color").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYNRRegister(model, Val);
            }

        }

        private void scale_enh0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh0_KeyDown(sender, keyEnter);
        }

        private void scale_ynr_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_ynr_man.Text))
            { 
                if (XChipYnr.Exists(c => c.NameType.ToLower() == $"scale_ynr_man".ToLower()))
                {
                    var model = XChipYnr.Find(c => c.NameType.ToLower() == $"scale_ynr_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_ynr_man.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void scale_ynr_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_ynr_man_KeyDown(sender, keyEnter);
        }

        private void scale_enh_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_enh_man.Text))
            {
                
                if (XChipYnr.Exists(c => c.NameType.ToLower() == $"scale_enh_man".ToLower()))
                {
                    var model = XChipYnr.Find(c => c.NameType.ToLower() == $"scale_enh_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_enh_man.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void scale_enh_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_man_KeyDown(sender, keyEnter);
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            isRead = true;
            WaitBefore.Start("读取中", "正在加载中", 10);
            //var Mode_switchvalue = SerialSend.ReadRegister(0x80301700, sPortTemp);
            //if ((Mode_switchvalue & 0x80) == 0x80)
            //{
            //    Mode_switch.SelectedIndex = 1;
            //}
            //else
            //{
            //    Mode_switch.SelectedIndex = 0;
            //}
            //string nameType = string.Empty;
            //for (int i = 0; i < XChipYnr.Count; i++)
            //{

            //    var type = AppHelper.NameTypeToString(XChipYnr[i].NameType);

            //    //加上单选框的_en
            //    if (XChipYnr[i].ControlType == "1")
            //    {
            //        type = XChipYnr[i].NameType;
            //    }
            //    try
            //    {

            //        Control col = this.Controls.Find(type, true)[0];
            //        if (nameType == type) continue;
            //        nameType = type;

            //        if (col is TextEdit)
            //        {
            //            //过滤掉指定寄存器
            //            if (listfiltration.Exists(c => c == col.Name.ToString()))
            //            {
            //                continue;
            //            }
            //            var nameList = XChipYnr.Where(c => c.NameType.ToLower().Contains(type)).ToList();
            //            long tempU = 0;
            //            foreach (var nitem in nameList)
            //            {
            //                tempU += GetYNRRegister(nitem.NameType);
            //            }
            //            col.Text = tempU.ToString("X");
            //        }
            //        else if (col is CheckEdit)
            //        {
            //            (col as CheckEdit).Checked = (GetYNRRegister(type) == 0);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}

            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipYnr.Count; i++)
            {
                if (XChipYnr[i].NameType.Contains("scale_enh0"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipYnr[i].NameType);
                if (NameList.Exists(c => c.ToLower()==(type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipYnr[i].ControlType == "1")
                {
                    type = XChipYnr[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {

                        var nList = XChipYnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipYnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
                            }                        
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }
                            if (string.IsNullOrEmpty(Val))
                            {
                                
                                nList = XChipYnr.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                }
                                

                            }
                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipYnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }




            //for (int i = 0; i < XChipCnr.Count; i++)
            //{

            //    var type = AppHelper.NameTypeToString(XChipCnr[i].NameType);
            //    //加上单选框的_en
            //    if (XChipCnr[i].ControlType == "1")
            //    {
            //        type = XChipCnr[i].NameType;
            //    }
            //    try
            //    {
                    
            //        Control col = this.Controls.Find(type, true)[0];
            //        if (nameType == type) continue;
            //        nameType = type;

            //        if (col is TextEdit)
            //        {
            //            var nameList = XChipCnr.Where(c => c.NameType.ToLower().Contains(type)).ToList();
            //            long tempU = 0;
            //            foreach (var nitem in nameList)
            //            {
            //                tempU += GetCNRRegister(nitem.NameType);
            //            }
            //            col.Text = tempU.ToString("X");
            //        }
            //        else if (col is CheckEdit)
            //        {
            //            (col as CheckEdit).Checked = (GetCNRRegister(type) == 0);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}

            NameList = new List<string>();

            for (int i = 0; i < XChipCnr.Count; i++)
            {
                if (XChipCnr[i].NameType.Contains("scale_cnr_man"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipCnr[i].NameType);
                if (NameList.Exists(c => c.ToLower()==(type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipCnr[i].ControlType == "1")
                {
                    type = XChipCnr[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {

                        var nList = XChipCnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipCnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }

                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipCnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }


            //for (int i = 0; i < XChipDnr.Count; i++)
            //{

            //    var type = AppHelper.NameTypeToString(XChipDnr[i].NameType);
            //    //加上单选框的_en
            //    if (XChipDnr[i].ControlType == "1")
            //    {
            //        type = XChipDnr[i].NameType;
            //    }
            //    try
            //    {

            //        Control col = this.Controls.Find(type, true)[0];
            //        if (nameType == type) continue;
            //        nameType = type;

            //        if (col is TextEdit)
            //        {
            //            var nameList = XChipDnr.Where(c => c.NameType.ToLower().Contains(type)).ToList();
            //            long tempU = 0;
            //            foreach (var nitem in nameList)
            //            {
            //                tempU += GetDNRRegister(nitem.NameType);
            //            }
            //            col.Text = tempU.ToString("X");
            //        }
            //        else if (col is CheckEdit)
            //        {
            //            (col as CheckEdit).Checked = (GetDNRRegister(type) == 0);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}



            NameList = new List<string>();

            for (int i = 0; i < XChipDnr.Count; i++)
            {
                if (XChipDnr[i].NameType.Contains("Red_pixel_num_thr"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipDnr[i].NameType);
                if (NameList.Exists(c => c.ToLower()==(type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipDnr[i].ControlType == "1")
                {
                    type = XChipDnr[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {

                        var nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m2")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m2")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }

                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipDnr.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }
           
            isRead = false;
            WaitBefore.Close();
            EnShowHide();

        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()) && !listc.Exists(c => c.Name.ToLower() == (fieldInfo[i].Name.ToLower())))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }
     

        private long GetCNRRegister(string nameType)
        { 
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipCnr.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipCnr.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }

        private long GetDNRRegister(string nameType)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return -1;
            }

            if (XChipDnr.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == nameType.ToLower());
                var Val = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                if (model.ControlType.Contains("1"))
                {
                    return BitsHelp.GetBitsCheckedToBool(model.Bits, model.Hex, Val.ToString("X2"));
                }
                else
                {
                    return BitsHelp.GetBitsToUint(model.Bits, model.Hex, Val.ToString("X2"));
                }
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }

      
        private void scale_cnr_list0_KeyDown(object sender, KeyEventArgs e)
        {
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCNRRegister($"scale_cnr_list{txtEdit.Tag.ToString()}", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (XChipCnr.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCnr.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetYNRRegister(model, Val);
            }
        }

        private void scale_cnr_list0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_cnr_list0_KeyDown(sender, keyEnter);
        }

        private void green_keep_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
             
            if (XChipCnr.Exists(c => c.NameType.ToLower() == $"green_keep_en".ToLower()))
            {
                var model = XChipCnr.Find(c => c.NameType.ToLower() == $"green_keep_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), green_keep_en.Checked);
                SetYNRRegister(model, Val);
            }
            EnShowHide();
        }

        private void scale_cnr_man_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
           
            if (XChipCnr.Exists(c => c.NameType.ToLower() == $"scale_cnr_man_en".ToLower()))
            {
                var model = XChipCnr.Find(c => c.NameType.ToLower() == $"scale_cnr_man_en".ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_cnr_man_en.Checked);
                SetYNRRegister(model, Val);
            }
            EnShowHide();
        }

        private void scale_cnr_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_cnr_man.Text))
            {
                var nHigh = Convert.ToUInt32(scale_cnr_man.Text, 16);
                 
                if (XChipCnr.Exists(c => c.NameType.ToLower() == $"scale_cnr_man".ToLower()))
                {
                    var model = XChipCnr.Find(c => c.NameType.ToLower() == $"scale_cnr_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_cnr_man.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void scale_cnr_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_cnr_man_KeyDown(sender, keyEnter);
        }

        private void green_u_up_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(green_u_up.Text))
            {
                var nHigh = Convert.ToUInt32(green_u_up.Text, 16);
                 
                if (XChipCnr.Exists(c => c.NameType.ToLower() == $"green_u_up".ToLower()))
                {
                    var model = XChipCnr.Find(c => c.NameType.ToLower() == $"green_u_up".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, green_u_up.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void green_u_up_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            green_u_up_KeyDown(sender, keyEnter);
        }

        private void green_v_up_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(green_v_up.Text))
            {
                var nHigh = Convert.ToUInt32(green_v_up.Text, 16);
                //SetCNRRegister("green_v_up", (ulong)nHigh);
                if (XChipCnr.Exists(c => c.NameType.ToLower() == $"green_v_up".ToLower()))
                {
                    var model = XChipCnr.Find(c => c.NameType.ToLower() == $"green_v_up".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, green_v_up.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void green_v_up_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            green_v_up_KeyDown(sender, keyEnter);
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_YNR_CNR_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                SerialSend.isDebug = false;
                StringBuilder sb = new StringBuilder();
                Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                    var tempList = Pe_dal.GetList(c => c.Module == "YNR" ).OrderBy(c => c.SortNum).ToList();
                    sb.Append("0xffff,0xfef1,\n");
                    sb.Append("\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 判断是否需要用白天的数据
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            //setShowMsg(item.RelationAddr);
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    tempList = Pe_dal.GetList(c => c.Module == "CNR").OrderBy(c => c.SortNum).ToList();
                   
                    sb.Append("\n");
                    sb.Append($"//{tempList.First().Module}\n");
                    foreach (var item in tempList)
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            #region 
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                            }
                            #endregion
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            //setShowMsg(item.RelationAddr);
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            return;
                        }
                    }
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
                    WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
                }
            }
            SerialSend.isDebug = true;
        }

       

        private void Uv_DNR_Manual_En_CheckedChanged(object sender, EventArgs e)
        {
           
            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.CheckEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), Uv_DNR_Manual_En.Checked);
                SetYNRRegister(model, Val);
            }
            if (Uv_DNR_Manual_En.CheckState == CheckState.Checked)
            {
                Uv_DNR_Manual_En.CheckState = CheckState.Checked;
                UvDnsManualShowHide(false);
            }
            else
            {
                Uv_DNR_Manual_En.CheckState = CheckState.Unchecked;
                UvDnsManualShowHide(true);
            }
        }

        private void Uv_DNR_Manual_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写           
            if (string.IsNullOrEmpty(Uv_DNR_Manual.Text)) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (XChipDnr.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipDnr.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, Uv_DNR_Manual.Text);
                SetYNRRegister(model, Val);
            }
        }

        private void Uv_Dnr0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            //if (null != sPortTemp && sPortTemp.IsOpen)
            {
                if (isRead) return;
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipDnr.Exists(c => c.NameType.ToLower() == txt.Name.ToLower()))
                {
                    var model = XChipDnr.Find(c => c.NameType.ToLower() == txt.Name.ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetYNRRegister(model, Val);
                }
            }
        }

        private void UvDnsManualShowHide(bool isBool)
        {
            Uv_Dnr0.Enabled = isBool;
            Uv_Dnr1.Enabled = isBool;
            Uv_Dnr2.Enabled = isBool;
            Uv_Dnr3.Enabled = isBool;
            Uv_Dnr4.Enabled = isBool;
            Uv_Dnr5.Enabled = isBool;
            Uv_Dnr6.Enabled = isBool;
            Uv_Dnr7.Enabled = isBool;
            Uv_Dnr8.Enabled = isBool;
            Uv_DNR_Manual.Enabled = !isBool;
        }

        private void Uv_Dnr0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Uv_Dnr0_Leave(sender, null);
            }
        }

        private void Uv_DNR_Manual_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Uv_DNR_Manual_Leave(sender, null);
            }
        }

        private void Mode_switch_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Mode_switch.EditValue.ToString() == "1")
            {
                ColorOrGray = "Color";
                labelControl9.Text = "scale_enh_Color";
            }
            else
            {
                ColorOrGray = "Gray";
                labelControl9.Text = "scale_enh_Gray";
            }
        }
        private void EnShowHide()
        {
            scale_enh_man.Enabled = scale_enh_man_en.Checked;
            scale_ynr_man.Enabled = scale_ynr_man_en.Checked;

            green_u_up.Enabled = green_keep_en.Checked;
            green_v_up.Enabled = green_keep_en.Checked;

            scale_cnr_man.Enabled = scale_cnr_man_en.Checked;

            scale_ynr0.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr1.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr2.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr3.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr4.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr5.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr6.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr7.Enabled = !scale_ynr_man_en.Checked;
            scale_ynr8.Enabled = !scale_ynr_man_en.Checked;

            scale_enh0.Enabled = !scale_enh_man_en.Checked;
            scale_enh1.Enabled = !scale_enh_man_en.Checked;
            scale_enh2.Enabled = !scale_enh_man_en.Checked;
            scale_enh3.Enabled = !scale_enh_man_en.Checked;
            scale_enh4.Enabled = !scale_enh_man_en.Checked;
            scale_enh5.Enabled = !scale_enh_man_en.Checked;
            scale_enh6.Enabled = !scale_enh_man_en.Checked;
            scale_enh7.Enabled = !scale_enh_man_en.Checked;
            scale_enh8.Enabled = !scale_enh_man_en.Checked;

            scale_cnr_list0.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list1.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list2.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list3.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list4.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list5.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list6.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list7.Enabled = !scale_cnr_man_en.Checked;
            scale_cnr_list8.Enabled = !scale_cnr_man_en.Checked;
        }
    }
}
